package project.crawler.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import project.model.adt.User;

public class UserParser {

	private static final Pattern CANNON_URL_PATTERN = Pattern
			.compile("\\Qhttp://stackoverflow.com/users/\\E" + "(\\d+)\\/(.+)");

	private static long getReputation(Element smallUserInfo) {
		Element elem = ParserUtils.getElement(smallUserInfo, "class",
				"reputation-score", "span");
		String str = elem.html();
		str = str.replace(",", "");
		return Long.parseLong(str);
	}

	public static User parseUser(String html) {
		Document doc = org.jsoup.parser.Parser.parse(html, "");

		String canonURL = ParserUtils.getCanonURL(doc.head());
		Matcher m = CANNON_URL_PATTERN.matcher(canonURL);
		if (!m.matches()) {
			throw new RuntimeException(
					"canonURL does not match CANNON_URL_PATTERN: " + canonURL);
		}
		long id = Long.parseLong(m.group(1));
		String name = m.group(2);

		Element smallUserInfo = doc.body().getElementById("small-user-info");

		long reputation = getReputation(smallUserInfo);

		long numMonths = getNumMonths(smallUserInfo);

		return new User(id, name, reputation, numMonths);
	}

	private static long getNumMonths(Element smallUserInfo) {
		Elements elems = smallUserInfo
				.getElementsContainingOwnText("member for");
		Element td1 = ParserUtils.assertOneElement(elems, "td");
		Element td2 = td1.nextElementSibling();
		String fromDate = td2.attr("title");

		long d1 = ParserUtils.parseDate(fromDate);
		long d2 = ParserUtils.parseDate("2014-12-31 00:00:00Z");

		return (d2 - d1) / (1000L * 60L * 60L * 24L * 30L);
	}

}
